package utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

import beans.HttpConfig;

public class FileOper {
		public static String readFile(String filePath){
			StringBuilder sb=new StringBuilder();
			try {
				//StringBuilder sb=new StringBuilder();
				//FileReader fr= new FileReader(filePath);
				BufferedReader bfr= new BufferedReader( new InputStreamReader(new FileInputStream(filePath),"UTF-8"));
				String re=null;
				while((re=bfr.readLine())!=null){
					sb.append(re);
				}
				//fr.close();
				bfr.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return sb.toString();
		}
		public static String writeFile(String filePath,String data ){
			try {
				BufferedWriter  out= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath),"UTF-8"));
				out.write(data);
				out.newLine();
				out.flush();
				return filePath;
			} catch (UnsupportedEncodingException | FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		public static boolean deleteAndCreateNewFile(String filePath){
			//boolean Exist=false;
			File f= new File(filePath);
			
			try {
				if(f.exists()){
					f.delete();
				}
				f.createNewFile();
				return true;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return false;
		}
		public static String readTaskJson(String filePath){
			return readFile(filePath);
		}
		public static String genTaskJsonFilePath(){
			return HttpConfig.taskJsonFileUri+UUID.randomUUID()+".json";
		}
		public static String writeTaskJson(String filePath,String data){			
			deleteAndCreateNewFile(filePath);
			if(data==null|| data.length()==0)
				data="{}";
			return writeFile(filePath,data);
		}
}
